//
//  BuyOnlineViewController.m
//  EasyToo
//
//  Created by Jr Lan on 13-9-1.
//
//

#import "BuyOnlineViewController.h"
#import "DeviceUtil.h"
#import "ConfirmMovieViewController.h"
#import "NetworkAlertView.h"


@interface BuyOnlineViewController ()

@end

@implementation BuyOnlineViewController
{
    UIAlertView *_baseAlert;
    
    NSMutableArray *_seatsList;
    NSMutableArray *_chooseseats;
    
    ChooseSeatsView *_chooseView;
    ChoosenView *_choosenview;
    
    NSInteger maxrownum;
    NSInteger maxcolnum;
    
    NSMutableString *seatsstr;
    NSMutableString *pricestr;
    NSMutableString *feesstr;
}

- (void)dealloc
{
    [_seatsList release];
    [_chooseseats release];
    [_chooseView release];
    [_choosenview release];
    [seatsstr release];
    [pricestr release];
    [feesstr release];
    
    _seatsList = nil;
    _chooseseats = nil;
    _chooseView = nil;
    _choosenview = nil;
    seatsstr = nil;
    pricestr = nil;
    feesstr = nil;
    
    [super dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        seatsstr = [[NSMutableString alloc]init];
        pricestr = [[NSMutableString alloc]init];
        feesstr = [[NSMutableString alloc]init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    //等待网络
    NetworkAlertView *networking = [NetworkAlertView shareView];
    [networking showNetView];
    
    //请求座位详情
    MovieManager *moviemanager = [MovieManager shareManager];
    moviemanager.delegate = self;
    [moviemanager qryOnlineDetail:self.foretellId hallId:self.hallId cinemaId:self.cinemaId];
    //[moviemanager qryOnlineDetail:@"2281215" hallId:@"08" cinemaId:@"497"];
    
    //初始化数据
    _chooseseats = [[NSMutableArray alloc]init];
    _seatsList = [[NSMutableArray alloc]init];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//加载视图
- (void)init_view
{
    self.title = @"电影票";
    
    //加载图像
    UIImageView *imgview  = [[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"film_middle_03"]]autorelease];
    imgview.frame = CGRectMake(0, ADJUST_IOS7STATUES_HIGHT+60, [DeviceUtil getScreenWidth], 60);
    [self.view addSubview:imgview];
    
    //加载电影
    UILabel *movieLbl = [[[UILabel alloc]initWithFrame:CGRectMake(10, ADJUST_IOS7STATUES_HIGHT+60, 60, 40)]autorelease];
    movieLbl.text = self.filmName;
    movieLbl.font = [UIFont systemFontOfSize:15];
    movieLbl.backgroundColor = [UIColor clearColor];
    movieLbl.textColor = [UIColor whiteColor];
    movieLbl.adjustsFontSizeToFitWidth = YES;
    movieLbl.textAlignment = NSTextAlignmentCenter;
    movieLbl.lineBreakMode = UILineBreakModeWordWrap;
    movieLbl.numberOfLines = 0;
    [self.view addSubview:movieLbl];
    
    //加载影院
    UILabel *cinemaLbl = [[[UILabel alloc]initWithFrame:CGRectMake(80, ADJUST_IOS7STATUES_HIGHT+60, 160, 60)]autorelease];
    cinemaLbl.text = [NSString stringWithFormat:@"%@\n屏幕方向", self.cinemaName];
    cinemaLbl.font = [UIFont systemFontOfSize:15];
    cinemaLbl.backgroundColor = [UIColor clearColor];
    cinemaLbl.textColor = [UIColor whiteColor];
    cinemaLbl.adjustsFontSizeToFitWidth = YES;
    cinemaLbl.textAlignment = NSTextAlignmentCenter;
    cinemaLbl.lineBreakMode = UILineBreakModeWordWrap;
    cinemaLbl.numberOfLines = 0;
    [self.view addSubview:cinemaLbl];
    
    //加载时间
    UILabel *timeLbl = [[[UILabel alloc]initWithFrame:CGRectMake(250, ADJUST_IOS7STATUES_HIGHT+60, 60, 40)]autorelease];
    timeLbl.text = self.time;
    timeLbl.font = [UIFont systemFontOfSize:15];
    timeLbl.backgroundColor = [UIColor clearColor];
    timeLbl.textColor = [UIColor whiteColor];
    timeLbl.adjustsFontSizeToFitWidth = YES;
    timeLbl.textAlignment = NSTextAlignmentCenter;
    timeLbl.lineBreakMode = UILineBreakModeWordWrap;
    timeLbl.numberOfLines = 0;
    [self.view addSubview:timeLbl];
    
    //加载座位
    [self initSeat];
    [self addSeat];
    [self initSeatList];
    [self addSeatList];
    
    //前往购买
    UIButton *nextStep =[[UIButton alloc]initWithFrame:CGRectMake(00, ADJUST_IOS7STATUES_HIGHT+380, 320, 30)];
    [nextStep setBackgroundImage:[UIImage imageNamed:@"xyb"] forState:UIControlStateNormal];
    [nextStep setTitle:@"锁定座位" forState:UIControlStateNormal];
    [self.view addSubview:nextStep];
    [nextStep addTarget:self action:@selector(clickNextDelegate) forControlEvents:UIControlEventTouchUpInside];

}

//加载座位
- (void)initSeat
{
    _chooseView = [[ChooseSeatsView alloc] initWithFrame:CGRectMake(0, ADJUST_IOS7STATUES_HIGHT+120, [DeviceUtil getScreenWidth], 200)];
    _chooseView.choosedelegate = self;
    _chooseView.scrollEnabled = YES; //只能一个方向滑动
    _chooseView.directionalLockEnabled = YES; //只能一个方向滑动
    _chooseView.pagingEnabled = NO; //是否翻页
    _chooseView.showsVerticalScrollIndicator =YES; //垂直方向的滚动指示
    _chooseView.indicatorStyle = UIScrollViewIndicatorStyleWhite;//滚动指示的风格
    _chooseView.showsHorizontalScrollIndicator = NO;//水平方向的滚动指示
}
- (void)addSeat
{
    if (_chooseView)
    {
        _chooseView.seatlist = _seatsList;
        [_chooseView init_view];
        
        NSInteger width = [DeviceUtil getScreenWidth];
        int imglen = width / maxcolnum * 0.9;
        
        [_chooseView setContentSize:CGSizeMake(320, imglen*maxrownum)];
        [self.view addSubview:_chooseView];
    }
}
- (void)removeSeat
{
    if (_chooseView)
    {
        [_chooseView removeFromSuperview];
    }
}

//加载信息
- (void)initSeatList
{
    _choosenview = [[ChoosenView alloc] initWithFrame:CGRectMake(0, ADJUST_IOS7STATUES_HIGHT+320, [DeviceUtil getScreenWidth], 60)];
}
- (void)addSeatList
{
    if (_choosenview)
    {
        _choosenview.seatlist = _chooseseats;
        [_choosenview init_view];
        [self.view addSubview:_choosenview];
    }
}
- (void)removeSeatList
{
    if (_choosenview)
    {
        [_choosenview removeFromSuperview];
    }
}

#pragma mark chooseviewdelegate

//选择座位
- (void)addTicketDelegate:(NSString*)index1 index2:(NSString*)index2 arraylist:(NSMutableArray*)seatlist
{
    _seatsList = seatlist;
    
    NSMutableArray *tmparray = [[[NSMutableArray alloc]initWithObjects:index1, index2, nil]autorelease];
    [_chooseseats addObject:tmparray];
    
    //重新加载座位表
    [self removeSeat];
    [self addSeat];
    
    //重新加载底部座位
    [self removeSeatList];
    [self addSeatList];
}

//反选择座位
- (void)delTicketDelegate:(NSString*)index1 index2:(NSString*)index2 arraylist:(NSMutableArray*)seatlist
{
    _seatsList = seatlist;
    
    NSMutableArray *tmparray = [[[NSMutableArray alloc]initWithObjects:index1, index2, nil]autorelease];
    [_chooseseats removeObject:tmparray];
    
    //重新加载座位表
    [self removeSeat];
    [self addSeat];
    
    //重新加载底部座位
    [self removeSeatList];
    [self addSeatList];
}

#pragma mark payviewdelegate
//跳转到支付
- (void)clickNextDelegate
{
    //已选座位信息
    NSInteger count = [_chooseseats count];
    
    for (int i = 0; i < count; i++) {
        int indexi = [[[_chooseseats objectAtIndex:i]objectAtIndex:0] intValue] + 1;
        int indexj = [[[_chooseseats objectAtIndex:i]objectAtIndex:1] intValue] + 1;
        NSString *tempstr;
        NSString *tempprice;
        NSString *tempfees;
        
        NSString *subprice = [NSString stringWithFormat:@"%d", [[self.price substringFromIndex:1] intValue]*100 ];
        
        if (i == (count-1)) {
            tempprice = [NSString stringWithFormat:@"%@", subprice];
            
            if (indexj >= 10) {
                tempstr = [NSString stringWithFormat:@"%d:%d", indexi, indexj];
            } else {
                tempstr = [NSString stringWithFormat:@"%d:0%d", indexi, indexj];
            }
            
            tempfees = self.fees;
        } else {
            tempprice = [NSString stringWithFormat:@"%@|", subprice];
            
            if (indexj >= 10) {
                tempstr = [NSString stringWithFormat:@"%d:%d|", indexi, indexj];
            } else {
                tempstr = [NSString stringWithFormat:@"%d:0%d|", indexi, indexj];
            }
            
            tempfees = [NSString stringWithFormat:@"%@|", self.fees];
        }
        [pricestr appendString:tempprice];
        [seatsstr appendString:tempstr];
        [feesstr appendString:tempfees];
    }
    
    //请求座位详情
    MovieManager *moviemanager = [MovieManager shareManager];
    moviemanager.delegate = self;

    //等待
    NetworkAlertView *networking = [NetworkAlertView shareView];
    [networking showNetView];
    
    [moviemanager buyOnlineTicket:self.foretellId seatIds:seatsstr fees:self.fees prices:pricestr count:[NSString stringWithFormat:@"%d", count]];
}

#pragma networking
//查看在线座位
- (void)qryOnlieSeatsFinish:(BOOL)isSuccess CinemaSeatInfo:(CinemaSeatInfo*)cinemaArray
{
    //找到影院位子的长和宽
    maxrownum = 0;
    maxcolnum = 0;
    for (int i = 0; i < [cinemaArray.SeatList count]; i++) {
        SeatInfo *seatInfo = [cinemaArray.SeatList objectAtIndex:i];
        int seatrow = [seatInfo.rowId intValue];
        int seatcolumn = [seatInfo.columnId intValue];
        if (maxrownum < seatrow) {
            maxrownum = seatrow;
        }
        if (maxcolnum < seatcolumn) {
            maxcolnum = seatcolumn;
        }
    }

    //初始化位子
    for (int i = 0; i < maxrownum; i++)
    {
        NSMutableArray *columnArray = [[NSMutableArray alloc]init];
        for (int j = 0; j < maxcolnum; j++) {
            [columnArray addObject:@"Y"];
        }
        [_seatsList addObject:columnArray];
        [columnArray release];
    }

    //座位损坏标志：Y损坏(不显示) N未损坏 W表示已被选择（其它用户） S已选择（本用户）
    for (int i = 0; i < [cinemaArray.SeatList count]; i ++) {
        SeatInfo *seatInfo = [cinemaArray.SeatList objectAtIndex:i];
        int seatrow = [seatInfo.rowId intValue] - 1;
        int seatcolumn = [seatInfo.columnId intValue] - 1;
        [[_seatsList objectAtIndex:seatrow]replaceObjectAtIndex:seatcolumn withObject:seatInfo.damagedFlag];
    }

    //加载已选择位子
    for (int i = 0; i < [cinemaArray.UsedSeatList count]; i ++) {
        UsedSeatInfo *seatInfo = [cinemaArray.UsedSeatList objectAtIndex:i];
        int seatrow = [seatInfo.rowId intValue] - 1;
        int seatcolumn = [seatInfo.columnId intValue] - 1;
        [[_seatsList objectAtIndex:seatrow]replaceObjectAtIndex:seatcolumn withObject:@"W"];
    }
    
    //取消等待
    NetworkAlertView *networking = [NetworkAlertView shareView];
    [networking delView];
    
    //加载视图
    [self init_view];
    
}


//购买在线座位
- (void)buyOnlineTicket:(BOOL)isSuccess
                orderId:(NSString*)orderId
                     rk:(NSString*)rk
{
    //取消等待
    NetworkAlertView *networking = [NetworkAlertView shareView];
    [networking delView];
    
    if (isSuccess) {
        ConfirmMovieViewController *confirmController = [[ConfirmMovieViewController alloc] init];
    
        NSInteger count = [_chooseseats count];
        confirmController.count = [NSString stringWithFormat:@"%d", count];
        confirmController.foretellId = self.foretellId;
        confirmController.seatIds = seatsstr;
        confirmController.prices = pricestr;
        confirmController.fees = feesstr;
        
        confirmController.filmName = self.filmName;
        confirmController.cinemaName = self.cinemaName;
        confirmController.hallName = self.hallName;
        confirmController.time = self.time;
        
        confirmController.orderId = orderId;
        confirmController.rk = rk;
        
        [self.navigationController pushViewController:confirmController animated:YES];
        [confirmController release];

    } else {
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"锁定座位失败" message:@"请重新锁定座位"  delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
    }
}

- (void) performDismiss: (NSTimer *)timer {
    [_baseAlert dismissWithClickedButtonIndex:0 animated:NO];//important
    [_baseAlert release];
    _baseAlert = NULL;
}

@end









